package com.pl.action;  

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Producer;
import com.pl.service.ManagePageService;
import com.pl.service.ManageUserService;

/**
 * 
 */
/**
 * class name:LoginAction <BR>
 * class description: please write your description <BR>
 * Remark: <BR>
 * @version 1.00 2019年8月5日
 * @author JFTT)wangjian
 */
@Controller
@RequestMapping(value="cookie")
public class CookieLoginAction {

	private static Logger log = LogManager.getLogger();
	
	@Resource(name="manageUserService")
	private ManageUserService manageUserService;
	
	@Resource(name="managePageService")
	private ManagePageService managePageService;

	
	/**
	 * 登录页面
	 */
	@RequestMapping(value="loginPage")
	public String loginPage(HttpServletRequest request){
		
		return "login/login";
	}
	
	/**
	 * 登陆
	 * @throws IOException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="login")
	@ResponseBody
	public void login(HttpServletRequest request, String userName, String password, String imageCode) throws UnsupportedEncodingException, IOException{
		// 连接地址（通过阅读html源代码获得，即为登陆表单提交的URL）
		String surl = "http://127.0.0.1:8888/PortalLogin/login";  
		/** 
		* 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如： // Using 
		* java.net.URL and //java.net.URLConnection 
		*/  
		URL url = new URL(surl);  
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
		/** 
		* 然后把连接设为输出模式。URLConnection通常作为输入来使用，比如下载一个Web页。 
		* 通过把URLConnection设为输出，你可以把数据向你个Web页传送。下面是如何做： 
		*/  
		connection.setDoOutput(true);  //打开输出，向服务器输出参数（POST方式、字节）（写参数之前应先将参数的字节长度设置到配置"Content-Length"<字节长度>）
		connection.setDoInput(true);//打开输入，从服务器读取返回数据
		connection.setRequestMethod("POST"); //设置登录模式为POST（字符串大写）
		connection.setInstanceFollowRedirects(false); 
		connection.connect();
		/** 
		* 最后，为了得到OutputStream，简单起见，把它约束在Writer并且放入POST信息中，例如： ... 
		*/  
		OutputStreamWriter out = new OutputStreamWriter(connection  
		      .getOutputStream(), "utf-8");  
		//其中的loginName和loginPassword也是阅读html代码得知的，即为表单中对应的参数名称  
		out.write("userName=admin&password=1234"); // post的关键所在！  
		//remember to clean up  
		out.flush();  
		out.close();  
		//取得cookie，相当于记录了身份，供下次访问时使用  
		//HttpURLConnection.getHeaderFields()).get("Set-Cookie")用于迭代读取Cookie，为以后使用
		//HttpURLConnection.getHeaderField("Set-Cookie")也可用于读取Cookie，但不一定能读取完全
		String cookieVal = connection.getHeaderField("Set-Cookie");  //格式:JSESSIONID=541884418E77E7F07363CCEE91D4FF7E; Path=/
		connection.disconnect();
		//登陆成功后，即可访问其他URL了。
		String s = "http://192.168.5.40:8090/ylysystem/cms/systemsetting/u_cmsInput.sc?" +
		"buildType=date&maxResults=10&firstResult=0&buildContent=index" +
		"&beginDate=2013-03-13&endDate=2013-03-20";  
		//重新打开一个连接  
		url = new URL(s);  
		HttpURLConnection resumeConnection = (HttpURLConnection) url
		      .openConnection();  
		if (cookieVal != null) {  
		     //发送cookie信息上去，以表明自己的身份，否则会被认为没有权限  
		  resumeConnection.setRequestProperty("Cookie", cookieVal);//设置登陆配置
		}
		resumeConnection.connect();  
		InputStream urlStream = resumeConnection.getInputStream();  
		BufferedReader bufferedReader = new BufferedReader(  
		      new InputStreamReader(urlStream));  
		String ss = null;  
		String total = "";  
		while ((ss = bufferedReader.readLine()) != null) {  
		System.err.println(ss);
		total += ss;  
		}  
		IOUtils.write(total, new FileOutputStream("c:/index.html"));  
		bufferedReader.close(); 
	}
	
	
	@RequestMapping(value="login2")
	@ResponseBody
	public String login2(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException{
		 String loginname = "admin";
	        String password = "123456";
	        Cookie cookie1 = new Cookie("loginname",loginname);
//	        Cookie cookie1 = new Cookie("name", URLEncoder.encode("哈哈", "UTF-8"));//存中文信息的时候需要这样设置编码
	        if (loginname!=null||password!=null){
	            cookie1.setMaxAge(60*60);//这里设置设置有效时间，单位的秒，我这里是一小时
	            cookie1.setPath("/");//这里是之根目录下所有的目录都可以共享Cookie
	            response.addCookie(cookie1);//添加Cookie
	            return "system/index.jsp";
	        }
			return null;
	}
}
